package com.jiunuan.live.msg.provider.consumer.handler.impl;

import com.alibaba.fastjson2.JSON;
import com.jiunuan.live.im.constants.AppIdEnum;
import com.jiunuan.live.im.dto.ImMsgBody;
import com.jiunuan.live.im.router.interfaces.constants.ImMsgBizCodeEnum;
import com.jiunuan.live.im.router.interfaces.rpc.ImRouterRpc;
import com.jiunuan.live.living.interfaces.dto.LivingRoomReqDTO;
import com.jiunuan.live.living.interfaces.rpc.ILivingRoomRpc;
import com.jiunuan.live.msg.dto.MessageDTO;
import com.jiunuan.live.msg.provider.consumer.handler.MessageHandler;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author: JiuNuan
 * @CreateTime: 2024-08-16 16:58
 * @Description:
 */
@Component
public class SingleMessageHandlerImpl implements MessageHandler {
    @DubboReference
    private ImRouterRpc imRouterRpc;
    @DubboReference
    private ILivingRoomRpc livingRoomRpc;
    /**
     * 处理im服务投递过来的消息
     *
     * @param imMsgBody
     */
    @Override
    public void onMsgReceive(ImMsgBody imMsgBody) {
        int bizCode = imMsgBody.getBizCode();
        // todo 直播间的聊天消息测试阶段
        if(bizCode == ImMsgBizCodeEnum.LIVING_ROOM_IM_CHAT_MSG_BIZ.getCode()){
            // 一个人发送，n个人接收（群聊）
            // 根据roomId调用rpc方法，获取对应直播间的用户id
            // 创建一个list的imMsgBody对象
            // 直播间消息
            MessageDTO messageDTO = JSON.parseObject(imMsgBody.getData(), MessageDTO.class);
            Integer roomId = messageDTO.getRoomId();
            LivingRoomReqDTO reqDTO = new LivingRoomReqDTO();
            reqDTO.setRoomId(roomId);
            reqDTO.setAppId(imMsgBody.getAppId());
            //自己不用发
            List<Long> userIdList = livingRoomRpc.queryUserIdByRoomId(reqDTO).
                    stream().filter(x->!x.equals(imMsgBody.getUserId())).
                    collect(Collectors.toList());
            if(CollectionUtils.isEmpty(userIdList)){
                return;
            }
            List<ImMsgBody> imMsgBodies = new ArrayList<>();
            userIdList.forEach(userId ->{
                ImMsgBody respMsgBody = new ImMsgBody();
                respMsgBody.setUserId(userId);
                respMsgBody.setAppId(AppIdEnum.JIUNUAN_LIVE_BIZ.getCode());
                respMsgBody.setBizCode(ImMsgBizCodeEnum.LIVING_ROOM_IM_CHAT_MSG_BIZ.getCode());
                respMsgBody.setData(JSON.toJSONString(messageDTO));

                imMsgBodies.add(respMsgBody);
            });

            imRouterRpc.batchSendMsg(imMsgBodies);
        }else if(bizCode == 2){
            // 私聊消息
        } else if(bizCode == 3){
            // 礼物消息
        }
    }
}
